package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Yan
 * @date 2022/2/22
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    /**
     * 定义路径匹配器
     */
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求的url
        String requestUri = request.getRequestURI();

        log.info("拦截到的请求是：" + requestUri);


        //1.需要放行的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };


        //2.判断请求是否需要处理
        //3.不需要处理，就直接放行
        if(check(urls, requestUri)){
            log.info("本次请求不需要处理"+requestUri);
            chain.doFilter(request,response);
            return;
        }
        //4.判断是否已经登录
        Object id = request.getSession().getAttribute("employee");
        //后台登录放行
        if(ObjectUtils.isNotEmpty(id)){
            log.info("用户已经登录，用户ID为："+id);

            //设置值
            BaseContext.setCurrentId((Long)id);

            chain.doFilter(request,response);

            return;
        }
        //4-2、判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null ){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            chain.doFilter(request,response);
            return;
        }

        log.info("用户没登录");
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配，检查路径是否需要放行
     * @param urls
     * @param requestUrl
     * @return
     */
    private boolean check(String[] urls, String requestUrl) {
        //AntPathMatcher pathMatcher =new AntPathMatcher();也可以实现功能

        for (String url : urls) {
            if (PATH_MATCHER.match(url, requestUrl)) {
                return true;
            }
        }
        return false;
    }
}
